<template>
  <view class="page">
    <u-navbar
      :fixed="false"
      title="入库单"
      :autoBack="true"
      bgColor="transparent"
    ></u-navbar>
    <view class="form-data">
      <u--form labelPosition="left" :model="form">
        <u-form-item label="司机" borderBottom>
          <u--input
            v-model="form.F_PCYE_MulBase_ca9"
            disabledColor="#ffffff"
            placeholder="请填写司机"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="物流名称" borderBottom>
          <u--input
            v-model="form.F_PCYE_Text_qtr"
            disabledColor="#ffffff"
            placeholder="请填写物流名称"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="物流单号" borderBottom>
          <u--input
            v-model="form.F_PCYE_Text_83g"
            disabledColor="#ffffff"
            placeholder="请填写物流单号"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="箱数">
          <u--input
            v-model="form.F_PCYE_Text_pzg"
            type="number"
            disabledColor="#ffffff"
            placeholder="请填写箱数"
            border="none"
          ></u--input>
        </u-form-item>
      </u--form>
    </view>
    <view class="goods-box">
      <view class="title">商品列表</view>
      <view class="goods-data">
        <view
          class="goods-list"
          v-for="(item, index) in goodsList"
          :key="index"
          :id="'item-' + index"
        >
          <view class="list-name">
            <view class="name u-line-2"
              >{{ index + 1 }} . {{ item.FMaterialName }} ({{
                item["FMaterialId.FNumber"]
              }})</view
            >
            <u-icon name="photo" size="24" @click="imageBig(item)"></u-icon>
            <view class="" @click="toDelete(item, index)"
              ><u-icon name="trash" size="24"></u-icon
            ></view>
            <u-icon name="arrow-right" size="24" @click="toPage(item)"></u-icon>
          </view>
          <view class="list-price">
            <view class="number">
              <view class="">应收数量：{{ item.FMustQty }}</view>
            </view>
            <view class="number">
              <view class="">实收数量：</view>
              <u--input
                placeholder="请输入实收数量"
                v-model="item.FRealQty"
                border="bottom"
                @blur="FRealQtyBlur($event, index, item)"
              ></u--input>
            </view>
          </view>
          <view class="list-price">
            <view class="number"> 含税单价：{{ item.FTaxPrice }} </view>
            <view class="number">
              <view class="">税额：</view>
              <view class="">{{ item.FEntryTaxAmount }}</view>
            </view>
          </view>
          <view class="list-price">
            <view class="number">
              <view class="u-line-1">仓库：{{ item["FStockId.fname"] }}</view>
            </view>
            <view class="number">
              <view class="u-line-1"
                >仓位：<text
                  class="u-color-primary"
                  @click="searchPositionInfo(item, index)"
                  >{{ item.position || "请选择" }}</text
                ></view
              >
            </view>
          </view>
          <view class="list-price">
            <view class="number">
              <view class="">库存单位：</view>
              <view class="">{{ item["FUnitID.fname"] }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="bottom-box">
      <view class="list">
        <view class="three" @click="edit">提交入库单审核</view>
      </view>
    </view>

    <u-overlay :show="overlayShow" @click="overlayShow = false">
      <image class="overlayImage" :src="overlayImg" mode="widthFix"></image>
      <view class="saveBase" @click="saveBase">保存图片</view>
    </u-overlay>

    <u-picker
      :show="showposition"
      :columns="[positionList]"
      @cancel="showposition = false"
      @confirm="selectposition"
    ></u-picker>
    <u-modal :show="showModal" :content='resMsg' closeOnClickOverlay @confirm="showModal = false" @close="showModal = false"></u-modal>
  </view>
</template>

<script>
import {
  dynamicFormServiceSubmit,
  dynamicFormServiceSave,
  getExecuteServiceImg,
  getBaseImg,
  getOrderDetail,
  getPositionInfoByGoodsAnWarehouse,
} from "@/api/index";

export default {
  data() {
    return {
      showModal: false,
      resMsg: '',
      id: "",
      option: {},
      orgInfo: {},
      userInfo: {},
      goodsList: [],
      form: {
        F_PCYE_MulBase_ca9: '',
        F_PCYE_Text_qtr: '',
        F_PCYE_Text_83g: '',
        F_PCYE_Text_pzg: '',
      },
      overlayShow: false,
      overlayImg: "",
      showposition: false,
      positionList: [],
      goodsIndex: null,
    };
  },
  onLoad(option) {
    this.option = option;
    this.userInfo = uni.getStorageSync("userInfo");
    this.orgInfo = uni.getStorageSync("orgInfo");
    this.getForm();
  },
  onShow() {
  },
  methods: {
    getForm() {
      const option = this.option;
      const parameters = [
        {
          FormId: "STK_InStock",
          FilterString: `fid='${option.id}'`,
          FieldKeys: `fbillno,FDocumentStatus,FDate,FSupplierId.fname,F_PCYE_Text_pzg,F_PCYE_Text_qtr,F_PCYE_Text_83g,FStockOrgId.fname,
            FMaterialId.FNumber,FMaterialName,FUOM,FStockId.FNumber,FStockId.fname,FMustQty,FRealQty,FTaxPrice,FEntryTaxRate,FEntryTaxAmount,FAllAmount,
            FUnitID.fname,F_PCYE_BaseProperty_cgy,F_PCYE_Qty_qtr,F_PCYE_Qty_qtr1,Fid`,
          OrderString: "",
          TopRowCount: 0,
          StartRow: 0,
          Limit: 100,
          SubSystemId: "",
        },
      ];
      getOrderDetail({ parameters }).then((res) => {
        if (res.length) {
          this.goodsList = res;
        }
      });
    },
    searchPositionInfo(item, index) {
      const parameters = {
        ModelName: "",
        MaterialName: "",
        materialNumber: item["FMaterialId.FNumber"],
        stockOrgNumber: this.orgInfo.orgId,
        stockNumber: item["FStockId.FNumber"],
      };
      this.goodsIndex = index;
      uni.showLoading({ mask: true });
      getPositionInfoByGoodsAnWarehouse({ parameters: [parameters] }).then(
        (res) => {
          uni.hideLoading();
          if (res.IsSuccess !== "false") {
            this.showposition = true;
            this.positionList = res.stockList.map((v) => v.StockLocName);
          } else {
            this.jumpTo('/pages/adjustment/position', {FNumber: item["FStockId.FNumber"], type: '5'})
            // uni.showToast({
            //   title: res.msg,
            //   icon: "none",
            // });
            
          }
        }
      );
    },
    selectposition(e) {
      const item = this.goodsList[this.goodsIndex];
      item.position = e.value[0];
      this.$set(this.goodsList, this.goodsIndex, item);
      this.showposition = false;
    },
    // 修改 实收数量
    FRealQtyBlur(e, index, item) {
      item.FRealQty = e;
      this.$set(this.goodsList, index, item);
    },
    // 点击删除某条商品
    toDelete(item, index) {
      const that = this;
      if (that.goodsList.length == 1) {
        uni.showToast({
          title: "至少需要一个物料",
          icon: "none",
        });
        return;
      }
      const delGoodsContent =
        "是否删除：" +
        item.FMaterialName +
        "(" +
        item["FMaterialId.FNumber"] +
        ") 商品";
      uni.showModal({
        title: "提示",
        content: delGoodsContent,
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            that.goodsList.splice(index, 1);
          }
        },
      });
    },
    // 结算
    edit() {
      let flag = false
      for(let i in this.form) {
        if(this.form[i] === '') {
          flag = true
          break
        }
      }
      if(flag) {
        uni.showToast({
          title: '请完善基本信息',
          icon: 'none',
          mask: true
        })
        return
      }

      const that = this

      uni.showModal({
        title: "提示",
        content: '确定保存编辑并提交审核?',
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            const option = that.option;
            const form = that.form;

            const FInStockEntry = that.goodsList.map((v) => {
              return {
                FEntryID: v.Fid,
                "FMaterialId": {
                    "FNumber": v["FMaterialId.FNumber"]
                },
                F_PCYE_MulBase_ca9: form.F_PCYE_MulBase_ca9,
                F_PCYE_Text_qtr: form.F_PCYE_Text_qtr,
                F_PCYE_Text_83g: form.F_PCYE_Text_83g,
                F_PCYE_Text_pzg: form.F_PCYE_Text_pzg,
                "FStockLocId": {
                  // "FSTOCKLOCID__FF100001": {
                  //   "FNumber": v.position
                  // },
                  "FSTOCKLOCID__FF100002": {
                    "FNumber": v.position
                  },
                  "FSTOCKLOCID__FF100003": {
                    "FNumber": v.position
                  }
                },
                FRealQty: v.FRealQty,
              };
            });

            let parameters = [
              'STK_InStock',
              {
                IsDeleteEntry: "false",
                Model: {
                  FId: option.id,
                  F_PCYE_MulBase_ca9: form.F_PCYE_MulBase_ca9,
                  F_PCYE_Text_qtr: form.F_PCYE_Text_qtr,
                  F_PCYE_Text_83g: form.F_PCYE_Text_83g,
                  F_PCYE_Text_pzg: form.F_PCYE_Text_pzg,
                  FInStockEntry: FInStockEntry,
                }
              }
            ]

            uni.showLoading({ mask: true });
            dynamicFormServiceSave({ parameters }).then((res) => {
              uni.hideLoading()
              if (res.Result.ResponseStatus.IsSuccess) {
                that.submit()
              } else {
                that.resMsg = res.Result.ResponseStatus.Errors[0].Message
                that.showModal = true
              }
            });
                  
          }
        },
      });
    },
    // 提交审核
    submit() {
      const that = this
      let parameters = [
        "STK_InStock",
        {
          // CreateorgId: "0",
          Numbers: "",
          Ids: this.option.id,
        },
      ];
      uni.showLoading({ mask: true });
      dynamicFormServiceSubmit({ parameters: parameters }).then((res) => {
        uni.hideLoading()
        if (res.Result.ResponseStatus.IsSuccess) {
          uni.showToast({
            title: '审核提交成功',
            icon: "none",
          });
          setTimeout(function() {
            that.goBack()
          }, 1500)
        } else {
          that.resMsg = res.Result.ResponseStatus.Errors[0].Message
          that.showModal = true
        }
      });;
    },
    confirmUnit(e) {
      this.orderData.goodsList[this.unitIndex].priceUnit = e.value[0].name;
      this.orderData.goodsList[this.unitIndex].priceUnitId = e.value[0].id;
      this.unitShow = false;
    },
    imageBig(item) {
      uni.showLoading({ mask: true });
      getExecuteServiceImg({
        parameters: [
          {
            MaterialNumber: item["FMaterialId.FNumber"],
            token: uni.getStorageSync("token"),
          },
        ],
      }).then((res) => {
        function getQueryParam(url, param) {
          // 构造正则表达式，匹配 ? 或 & 后面跟随的参数名称和其值
          const regex = new RegExp("[?&]" + param + "=([^&#]*)", "i");
          const result = regex.exec(url);
          return result ? decodeURIComponent(result[1]) : null;
        }
        getBaseImg({
          parameters: [
            { FileId: getQueryParam(res.Url, "fileId"), StartIndex: 0 },
          ],
        }).then((bres) => {
          if (bres.Result.FilePart) {
            uni.hideLoading();
            this.overlayImg = "data:image/png;base64," + bres.Result.FilePart;
            this.overlayShow = true;
          } else {
            uni.showToast({
              title: "暂无图片",
              icon: "none",
            });
          }
        });
      });
    },
    saveBase64ToPhotoAlbum(base64Data) {
      // 1. 去除Base64头部信息（如："data:image/png;base64,"）
      const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");
      // 2. 转换为ArrayBuffer
      const arrayBuffer = uni.base64ToArrayBuffer(base64);
      // 3. 生成临时文件路径
      const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;
      // 4. 写入文件
      const fs = uni.getFileSystemManager();
      return new Promise((resolve, reject) => {
        fs.writeFile({
          filePath,
          data: arrayBuffer,
          encoding: "binary",
          success: () => {
            // 5. 保存到相册
            uni.saveImageToPhotosAlbum({
              filePath,
              success: () => resolve("保存成功"),
              fail: (err) => reject("保存失败，请检查权限：" + err.errMsg),
            });
          },
          fail: (err) => reject("文件写入失败：" + err.errMsg),
        });
      });
    },
    async saveBase() {
      try {
        const base64 = this.overlayImg;
        await this.saveBase64ToPhotoAlbum(base64);
        uni.showToast({ title: "保存成功", icon: "success" });
        console.error("保存图片成功");
      } catch (error) {
        console.error("保存图片失败 error：", error);
        uni.showToast({ title: error, icon: "none" });
        // 处理权限被拒绝的情况
        if (error.includes("authorize")) {
          uni.openSetting({}); // 引导用户打开权限设置
        }
      }
    },
    toPage(item) {
      console.log(item);
      this.jumpTo("/pages/inventoryQuery/inventoryQuery", {
        orgId: this.orgInfo.orgId,
        Materidal: item["FMaterialId.FNumber"],
        type: "1",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .u-form-item__body__left {
  width: auto !important;
  margin-right: 20rpx;
}
::v-deep .u-line {
  transform: scaleY(1) !important;
}
::v-deep .u-modal__content {
  padding-left: 28rpx !important;
  padding-right: 28rpx !important;
}
.page {
  width: 750rpx;
  min-height: 100vh;
  padding-bottom: 40rpx;
  .form-data {
    margin: 20rpx 30rpx 40rpx;
    padding: 16rpx 20rpx;
    background: #fff;
    border-radius: 20rpx;
    box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
  }
  .goods-box {
    margin-bottom: 260rpx;
    padding: 0 30rpx;
    .title {
      width: 100%;
      height: 36rpx;
      line-height: 36rpx;
      padding: 0 20rpx;
      margin-top: 20rpx;
      margin-bottom: 20rpx;
      border-left: 10rpx solid #3467fa;
      padding: 0 10rpx;
    }
    .goods-data {
      background: #fff;
      border-radius: 20rpx;
      box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
      .goods-list {
        width: 100%;
        padding: 20rpx 30rpx;
        border-bottom: 1px solid #d6d7d9;
        .list-name {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .name {
            width: 80%;
            font-size: 32rpx;
          }
        }
        .list-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin: 10rpx 0 20rpx;
          .price {
            width: 48%;
            display: flex;
            align-items: center;
          }
          .number {
            width: 48%;
            display: flex;
            align-items: center;
          }
          .textarea {
            width: 90%;
            display: flex;
            align-items: center;
          }
        }
        .form {
          display: flex;
          justify-content: space-between;
        }
        .stocksBtn {
          width: 230rpx;
          line-height: 50rpx;
          border: 1px solid #2677f0;
          border-radius: 10rpx;
          color: #2677f0;
          margin-left: auto;
        }
      }
      .goods-list:last-child {
        border: none;
      }
    }
    .goods-null {
      width: 100%;
      min-height: 500rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
  }
  .bottom-box {
    position: fixed;
    bottom: 0;
    background-color: #fff;
    width: 100%;
    z-index: 9;
    .top-list {
      background-color: #e4c5aa;
      padding: 20rpx 40rpx;
    }
    .list {
      display: flex;
      padding-bottom: 60rpx;
      font-size: 30rpx;
      background-color: #2677f0;
      .one {
        flex: 1;
        height: 100rpx;
        line-height: 100rpx;
        text-align: center;
      }
      .two {
        flex: 1;
        height: 100rpx;
        line-height: 100rpx;
        border-left: 1px solid #d7dbd6;
        border-right: 1px solid #d7dbd6;
        text-align: center;
      }
      .three {
        flex: 1;
        height: 100rpx;
        line-height: 100rpx;
        color: #fff;
        background-color: #2677f0;
        text-align: center;
      }
    }
  }
}
.goodsNum-modal {
  width: 100%;
  line-height: 50rpx;
}
.overlayImage {
  width: 80%;
  height: auto;
  margin: 300rpx auto 50rpx;
}
.saveBase {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  color: #fff;
  background-color: #2677f0;
  text-align: center;
  border-radius: 50rpx;
  margin: 0 auto;
}
.goodsView {
  width: 100%;
  .goods-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 45rpx;
    .sum {
      display: flex;
      align-items: center;
      margin-top: 16rpx;
      .actionDown {
        width: 50rpx;
        height: 50rpx;
        border-radius: 50rpx;
        border: 2rpx solid #266be9;
        font-size: 50rpx;
        color: #266be9;
        display: flex;
        justify-content: center;
      }
      .sum-text {
        margin: 0 10rpx;
      }
      .actionUp {
        width: 50rpx;
        height: 50rpx;
        border-radius: 50rpx;
        border: 2rpx solid #266be9;
        background-color: #266be9;
        font-size: 40rpx;
        color: #fff;
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>